import React, { useState, useEffect } from 'react';
import { useParams, useSearchParams, useNavigate } from 'react-router-dom';
import { message, Spin } from 'antd';
import { request } from '@/utils/request';
import BasicInfoForm from './components/BasicInfoForm';
import MediaFilesForm from './components/MediaFilesForm';
import CharacterProfilesForm from './components/CharacterProfilesForm';
import { PersonData } from '@/types/aiPerson';

// 编辑AI人物信息页面
const EditAiInformation: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const [searchParams] = useSearchParams();
    const navigate = useNavigate();

    // 获取URL参数
    const language = searchParams.get('language') || 'JP';

    // 状态管理
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [personData, setPersonData] = useState<PersonData | null>(null);

    // 获取人物信息
    const fetchPersonInformation = async () => {
        if (!id) {
            message.error('人物ID不能为空');
            return;
        }

        try {
            setLoading(true);
            console.log('请求参数:', { id, language });

            const response = await request.get('/api/ai-persons/getPersonInformation', {
                params: { id, language }
            });

            if (response.data.success) {
                const data = response.data.data;
                // 处理description字段，如果有空格键名则转换为description
                if (data[' '] && !data.description) {
                    data.description = data[' '];
                    delete data[' '];
                }
                setPersonData(data);
                console.log('获取人物信息成功:', data);
            } else {
                message.error('获取人物信息失败');
            }
        } catch (error: any) {
            console.error('获取人物信息错误:', error);
            message.error(error?.response?.data?.message || '获取人物信息失败');
        } finally {
            setLoading(false);
        }
    };

    // 保存人物信息
    const handleSave = async (updatedData: PersonData) => {
        try {
            setSaving(true);

            // 构造提交数据格式，匹配新的API数据结构
            const submitData = {
                id: updatedData.id,
                language: language,
                information: updatedData.information,
                country: updatedData.country,
                avatar: updatedData.avatar,
                image: updatedData.image,
                likes: updatedData.likes,
                comments: updatedData.comments,
                is_premium: updatedData.is_premium,
                description: updatedData.description,
                images: updatedData.images,
                videos: updatedData.videos,
                character_profiles: {
                    Emotions: updatedData.character_profiles.Emotions,
                    work_flow: updatedData.character_profiles.work_flow,
                    promptWord: updatedData.character_profiles.promptWord.replace(/[\r\n]+/g, ''),
                    aiPersion_id: updatedData.character_profiles.aiPersion_id,
                    voice_settings: updatedData.character_profiles.voice_settings,
                    persionImageDescription: updatedData.character_profiles.persionImageDescription,
                },
                type: updatedData.type,
            };

            console.log('提交的更新数据:', submitData);

            // 调用更新API
            const response = await request.post('/api/ai-persons/updatePerson', submitData);

            if (response.data.success) {
                message.success(response.data.message || '保存成功！');
                console.log('更新成功:', response.data);

                // 返回列表页面
                navigate('/Ai-persionList');
            } else {
                message.error(response.data.message || '保存失败');
            }

        } catch (error: any) {
            console.error('保存失败:', error);
            message.error(error?.response?.data?.message || '保存失败');
        } finally {
            setSaving(false);
        }
    };

    // 返回列表页面
    const handleBack = () => {
        navigate('/AiPersionList');
    };

    // 组件挂载时获取数据
    useEffect(() => {
        fetchPersonInformation();
    }, [id, language]);

    // 加载状态
    if (loading) {
        return (
            <div className="w-full max-w-7xl mx-auto bg-white rounded-2xl shadow-lg p-8 my-8">
                <div className="flex justify-center items-center h-64">
                    <Spin size="large" />
                    <span className="ml-3 text-lg text-gray-600">加载中...</span>
                </div>
            </div>
        );
    }

    // 数据为空状态
    if (!personData) {
        return (
            <div className="w-full max-w-7xl mx-auto bg-white rounded-2xl shadow-lg p-8 my-8">
                <div className="text-center">
                    <p className="text-lg text-gray-600">未找到相关人物信息</p>
                    <button
                        onClick={handleBack}
                        className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                    >
                        返回列表
                    </button>
                </div>
            </div>
        );
    }

    return (
        <div className="w-full max-w-7xl mx-auto bg-white rounded-2xl shadow-lg p-8 my-8">
            {/* 页面头部 */}
            <div className="mb-8">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-3xl font-bold text-gray-800">编辑AI人物信息</h2>
                        <p className="text-lg text-gray-600 mt-2">
                            人物ID: <span className="font-bold text-blue-600">{personData.id}</span>
                            {' | '}
                            语言区域: <span className="font-bold text-purple-600">{language === 'JP' ? '日文区' : '英文区'}</span>
                        </p>
                    </div>
                    <div className="flex gap-3">
                        <button
                            onClick={handleBack}
                            className="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-all"
                        >
                            返回列表
                        </button>
                        <button
                            onClick={() => handleSave(personData)}
                            disabled={saving}
                            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-all"
                        >
                            {saving ? '保存中...' : '保存修改'}
                        </button>
                    </div>
                </div>
            </div>

            {/* 表单内容 */}
            <div className="grid grid-cols-1 gap-8">
                {/* 基本信息表单 */}
                <BasicInfoForm
                    data={personData}
                    onChange={(data) => setPersonData(data)}
                />

                {/* 媒体文件表单 */}
                <MediaFilesForm
                    data={personData}
                    onChange={(data) => setPersonData(data)}
                />

                {/* 角色设定表单 */}
                <CharacterProfilesForm
                    data={personData}
                    onChange={(data) => setPersonData(data)}
                />
            </div>
        </div>
    );
};

export default EditAiInformation;